<template>
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="标题" prop="title" />
    <el-table-column label="标签" prop="labelIds" />
    <el-table-column align="right">
      <template #header>
        <el-form style="display: flex;">
          <el-input v-model="search" size="small" placeholder="请输入标题" width="100" />
        </el-form>
      </template>
      <template #default="scope">
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="centerDialogVisible" :title="titleDialog" width="500">
    <el-input v-model="centerDialogForm.tag" placeholder="标签"></el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="centerDialogVisible = false">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { getArticle, getTag } from '@/api/modules'
interface Card {
  id: number;               // 文章的 ID
  labelIds: number[];       // 标签 ID 数组
  title: string;            // 文章标题
  content: string;          // 文章内容
  authorId: number;         // 作者 ID
  viewCount?: number;        // 浏览量
  likeCount?: number;        // 点赞量
  commentCount?: number;     // 评论数量
}
interface User {
  createAt: string
  name: string
  id: number
}
const search = ref('')
const centerDialogVisible = ref(false)
const openDialog = ref(false)
const centerDialogForm = ref({ tag: '' })
const titleDialog = computed(() => (openDialog.value ? '新建标签' : '修改标签'))
const filterTableData = computed(() =>
  tableData.value.filter(
    (data: Card) =>
      !search.value ||
      data.title.toLowerCase().includes(search.value.toLowerCase())
  )
)
const tableData = ref<Card[]>([])
const handleDelete = (index: number, row: Card) => {
  console.log(index, row)
}
const fetchData = async () => {
  const res = await getArticle()
  const tagRes = await getTag()
  const labels = tagRes.data.data.labels
  const data = res.data.data.list;
  const labelMap = new Map<number, string>();
  labels.forEach((label: User) => {
    labelMap.set(label.id, label.name);
  });
  tableData.value = data.map((item: Card) => {
    const updatedLabelIds = item.labelIds.map((id) => labelMap.get(id) || `未知标签`);
    return {
      ...item,
      labelIds: updatedLabelIds,
    };
  });
}
onMounted(fetchData)
</script>
